const {
  app,
  BrowserWindow,
  dialog, // 调用原生对话框的模块
  Menu
} = require('electron')
const fs = require('fs')
const applicationMenu = require('./app-menu')
let windows = new Set() // 窗口储存队列
const creatWindow = exports.creatWindow = () => {
  let mainWindow = null
  let x = 0
  let y = 0
  let focusWinodw = BrowserWindow.getFocusedWindow()
  if (focusWinodw) {
    let [cx, cy] = focusWinodw.getPosition()
    x = cx + 10
    y = cy + 10
  }
  mainWindow = new BrowserWindow({
    x,
    y,
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    },
    show: false // 当首次创建窗口的时候，先将它隐藏起来
  })
  mainWindow.webContents.loadFile('./index.html')
  mainWindow.once('ready-to-show', () => {
    mainWindow.show() // DOM 就绪之后展示窗口
  })
  mainWindow.on('closed', (event) => {
    windows.delete(mainWindow)
    stopWatchingFile(mainWindow)
    mainWindow = null
  })

  mainWindow.on('close', event => {
   if (mainWindow.ifEdited) {
     event.preventDefault()
     const result = dialog.showMessageBoxSync(mainWindow, {
       type: 'warning',
       title: 'Quit with Unsave Change?',
       message: 'Your changes will be lost if you do not save',
       buttons: ['Quite Anyway', 'Cancel'],
       defaultId: 0,
       cancelId: 1
     })
     if (result === 0) {
       mainWindow.destroy()
     }
   }
  })
  windows.add(mainWindow)
  return mainWindow
}

const ifEdited = exports.ifEdited = (bo, targetWindow) => {
  targetWindow.ifEdited = bo
}
app.on('ready', () => {
  Menu.setApplicationMenu(applicationMenu)
  creatWindow()
})
// 当应用程序完全启动时触发
app.on('will-finish-launching', () => {
  console.log('i will open a file from recent files')
  app.on('open-file', (event, file) => {
    const win = creatWindow()
    win.once('ready-to-show', () => {
      openFile(win, file)
    })
  })
})

// 监听退出事件   并
app.on('window-all-closed', () => {
  if (process.platform === 'darwin') { // macOs 不退出，直接返回
    return
  }
  app.quit()
})
 // 在没有窗口时候打开一个窗口 macOS  此事件只会在 macOS系统中触发
 app.on('activate', (event, hasVisibleWindows) => {
  if (!hasVisibleWindows) {
    creatWindow()
  }
})

exports.getFileFromUser = function (targetWindow) {
  const files = dialog.showOpenDialogSync(targetWindow, {
    properties: ['openFile'],
    filters: [
      {
        name: 'Text Files',
        extensions: ['txt']
      },
      {
        name: 'Markdown Files',
        extensions: ['md', 'markdown']
      }
    ]
  })
  if (!files) {
    return
  }
  const file = files[0]
  openFile(targetWindow, file)
}


const openFile = exports.openFile = function(targetWindow, file) {
  const content = fs.readFileSync(file).toString()
  // 打开文件时，添加到最近打开的文档列表
  app.addRecentDocument(file)
  // 更新macOS系统的展示文件
  targetWindow.setRepresentedFilename(file)
  // 开启文件的变化监听
  startWatchingFile(targetWindow, file)
  targetWindow.webContents.send('file-opened', file, content)
}

// 保存文件
const saveHtml = exports.saveHtml = (targetWindow, content) => {
  const file = dialog.showSaveDialogSync(targetWindow, {
    title: '保存文件',
    defaultPath: app.getPath('exe'),
    filters: [
      {
        name: 'HTML Files',
        extensions: ['html', 'htm']
      }
    ]
  })

  if (!file) { return }
  fs.writeFileSync(file, content)
}

// 保存 markdown
const saveMarkdown = exports.saveMarkdown = (targetWindow, file, content) => {
  console.log(targetWindow, file, content)
  if (!file) {
    file = dialog.showSaveDialogSync(targetWindow, {
      title: '保存 Markdown',
      defaultPath: app.getPath('documents'),
      filters: [{name: 'Markdown Files', extensions: ['md', 'markdown']}],
    })
  }
  if (!file) return
  fs.writeFileSync(file, content)
  // 打开文件时，添加到最近打开的文档列表
  app.addRecentDocument(file)
  // 更新macOS系统的展示文件
  targetWindow.setRepresentedFilename(file)
  // 跟新 fullPath
  targetWindow.webContents.send('update-fullPath', file)
}

// 监控文件
const openFilesMap = new Map()
const startWatchingFile = (targetWindow, file) => {
  stopWatchingFile(targetWindow)

  const watcher = fs.watch(file, e => {
    if (e === 'change') {
      const content = fs.readFileSync(file).toString()
      // targetWindow.webContents.send('file-opened', file, content)
      targetWindow.webContents.send('file-changed', file, content)
    }
  })
  openFilesMap.set(targetWindow, watcher)
}
const stopWatchingFile = targetWindow => {
  if (openFilesMap.has(targetWindow)) {
    openFilesMap.get(targetWindow).close()
    openFilesMap.delete(targetWindow)
  }
}


